//
//  FirstTimeLaunch.m
//  Pocket Doctor alpha version
//
//  Created by Sherif, Yin, Taylor, Jacob, Anna, Mike on 11-10-25.
//  Copyright (c) 2011 __Sytjam__. All rights reserved.
//
//Class Description: First time set up of the application.
//                   save preference to database & set up the application - takes you to mail app when saving.
//
//Known Bugs: none.
//

#import "FirstTimeLaunch.h"
#import "MainMenu.h"
#import "Navigator.h"

@implementation FirstTimeLaunch

@synthesize secretAnswer, secretQuestion, secretQuestionButton, passcode, hint, done, doneQuestion, emailaddress;
@synthesize questionPicker, questions;
@synthesize mm, aD;

/*Sample Secret Question options
Load Sample Question Picker 
and hide everything else*/
- (IBAction)SecretQuestion:(id)sender{
    [secretQuestion resignFirstResponder];
    [secretAnswer resignFirstResponder];
    [passcode resignFirstResponder];
    [hint resignFirstResponder];
    [emailaddress resignFirstResponder];
    
    doneQuestion.hidden = false;
    questionPicker.hidden = false;
    
    secretQuestion.hidden = true;
    secretAnswer.hidden = true;
    passcode.hidden = true;
    hint.hidden = true;
    emailaddress.hidden = true;
    done.hidden = true;
}

/*Pressing done will write down the chosen row into question field and show other fields*/
- (IBAction)DoneSecretQuestion:(id)sender{
    doneQuestion.hidden = true;
    questionPicker.hidden = true;
    
    secretQuestion.hidden = false;
    secretAnswer.hidden = false;
    passcode.hidden = false;
    hint.hidden = false;
    emailaddress.hidden = false;
    done.hidden = false;
    
    //whatever row that was highlighted; text gets put into the secret question text field
    NSString *choice = [questions objectAtIndex:[questionPicker selectedRowInComponent:0]];
    secretQuestion.text = choice;
    
    [choice release];
}

//Picker Settings (Sample Question Picker Loading Functions)
- (NSInteger) numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return [questions count];
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    return [questions objectAtIndex:row];
}
//
//end of Sample Secret Question

/*Check if all fields were filled correctly
if all are successful; insert them into database*/
- (IBAction)DoneSelected:(id)sender{
    
    //Check Passcode and all other fields
    //other fields to be implemented (1/5 test cases)
    if([secretQuestion.text isEqualToString:@""]){
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Please write a Secret Question" delegate:nil cancelButtonTitle:@"Done" otherButtonTitles: nil];
        [alert show];
        [alert release];
    }
    else
        if([secretAnswer.text isEqualToString:@""]){
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Please write a Secret Answer" delegate:nil cancelButtonTitle:@"Done" otherButtonTitles: nil];
            [alert show];
            [alert release];   
        }
        else
            if([hint.text isEqualToString:@""]){
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Please write a hint" delegate:nil cancelButtonTitle:@"Done" otherButtonTitles: nil];
                [alert show];
                [alert release];
            }
            else
                if([passcode.text hasPrefix:@"0"]){
                    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Passcode can not start wit 0" delegate:nil cancelButtonTitle:@"Done" otherButtonTitles: nil];
                    [alert show];
                    [alert release];
                }
                else
                    if(passcode.text.length != 4){
                        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Must be 4 Digit Passcode" delegate:nil cancelButtonTitle:@"Done" otherButtonTitles: nil];
                        [alert show];
                        [alert release];
                    }
                    else{
                        if (([emailaddress.text rangeOfString:@"@"].location == NSNotFound) || ([emailaddress.text rangeOfString:@".c"].location == NSNotFound)) {
                            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Invalid e-mail address" delegate:nil cancelButtonTitle:@"Done" otherButtonTitles: nil];
                            [alert show];
                            [alert release]; 
                        }
                        else{
                            //Collect Variables
                            NSString *sq = [[NSString alloc]initWithFormat:secretQuestion.text]; //secret Question String
                            NSString *sa = [[NSString alloc]initWithFormat:[secretAnswer.text lowercaseString]];   //Secret Answer String
                            NSString *pc = [[NSString alloc]initWithFormat:passcode.text];       //PassCode String
                            NSString *h = [[NSString alloc]initWithFormat:hint.text];            //Hint

                            // Begin saving to database
                            sqlite3_stmt * statement;
                            NSString * enforceForeignKey = @"PRAGMA foreign_keys = 1";
                            const char * query_stmt = [enforceForeignKey UTF8String];
                            if (sqlite3_prepare_v2(aD.dbPointer, query_stmt, -1, &statement, NULL) == SQLITE_OK) {
                                sqlite3_step(statement);
                                if (sqlite3_errcode(aD.dbPointer) == SQLITE_OK) {
                                    sqlite3_finalize(statement);
                                }
                                else {
                                    //Couldn't enforce foreign key constraint.
                                }
                            }
                            [enforceForeignKey release];
                         
                            // rem holds value of whether notifications are on or off, as {0,1}
                            
                            //This is the SQL statement to add a medicine entry.
                            NSString *queryString = @"INSERT INTO Security (id, passcode, passcode_hint, secret_question, secret_answer) VALUES ('1', ?, ?, ?, ?);";
                            
                            NSString *queryString_2 = @"INSERT INTO Settings (id, clock_setting, date_setting, day_setting, email_address) VALUES ('1', '0', '0', '0', ?);";

                            
//                            CREATE TABLE Settings (id integer primary key unique, emergency_contact integer, clock_setting integer, date_setting integer, day_setting integer);"
                            
                            //(set)
                            //NSString *queryString = @"UPDATE Security SET passcode=?, passcode_hint=?, secret_question=?, secret_answer=? WHERE id=1;";
                            
                            // to be used with code from AddMedicine: (Load)
                            //NSString *loadSecurity = @"SELECT id, passcode, passcode_hint, secret_question, secret_answer FROM Security WHERE id=1;";
                            
                            
                            query_stmt = [queryString UTF8String];
                            if (sqlite3_prepare_v2(aD.dbPointer, query_stmt, -1, &statement, NULL) == SQLITE_OK){
                                sqlite3_bind_int(statement, 1, [pc intValue]);
                                sqlite3_bind_text(statement, 2, [h UTF8String],-1, SQLITE_TRANSIENT);
                                sqlite3_bind_text(statement, 3, [sq UTF8String],-1, SQLITE_TRANSIENT);
                                sqlite3_bind_text(statement, 4, [sa UTF8String],-1, SQLITE_TRANSIENT);
                                
                                sqlite3_step(statement);
                                if (sqlite3_errcode(aD.dbPointer) == SQLITE_DONE){
                                    sqlite3_finalize(statement);

                                }
                                else {
                                    // Pop up message for SQL error.
                                    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Unsuccessful" message:@"Can not set up security" delegate:nil cancelButtonTitle:@"Done" otherButtonTitles: nil];
                                    [alert show];
                                    [alert release];
                                }
                            }
                            [queryString release];
                            
                            query_stmt = [queryString_2 UTF8String];
                            if (sqlite3_prepare_v2(aD.dbPointer, query_stmt, -1, &statement, NULL) == SQLITE_OK){
                                
                                sqlite3_bind_text(statement, 1, [emailaddress.text UTF8String],-1, SQLITE_TRANSIENT);
                                
                                sqlite3_step(statement);
                                if (sqlite3_errcode(aD.dbPointer) == SQLITE_DONE){
                                    sqlite3_finalize(statement);
                                    
                                }
                            }


                            
                            // End saving to database
                            
                            NSString *message = [[NSString alloc]initWithFormat:@"Thank you for using Pocket Doctor.\n\nThis e-mail contains your personal passcode, secret question and answer. Please keep them safe. We are not responsible for you losing your passcode and secret answer.\n\nPasscode : %@\nSecret Answer to %@ is : %@\n\nEnjoy using Pocket Doctor\nSytjam", pc, sq, sa];
                            
                            NSString *to = emailaddress.text;
                            NSString *subject = @"Thank you for using Pocket Doctor";
                            
                            NSString *url = [NSString stringWithFormat:@"mailto:?to=%@&subject=%@&body=%@", [to stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding], [subject stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding], [message stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
                                             
                            [[UIApplication sharedApplication] openURL: [NSURL URLWithString: url]];
                            
                            [sq release];
                            [sa release];
                            [pc release];
                            [h release];
                            
                            //Go to Main Menu
                            MainMenu *mmObject = [[MainMenu alloc]initWithNibName:@"MainMenu" bundle:nil];
                            self.mm = mmObject;
                            [mmObject release];
                
                            mm.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
                            [self presentModalViewController:mm animated:YES];
                        }
                    }
}

//Support functions
/*Ensure the passcode is never longer than 4 digits*/
- (IBAction)checkPasscodeLength:(id)sender{
    if([passcode.text length] > 4){
        
        passcode.text = [passcode.text substringToIndex:4];
        
        //Resign all keyboards from screen
        [secretQuestion resignFirstResponder];
        [secretAnswer resignFirstResponder];
        [passcode resignFirstResponder];
        [hint resignFirstResponder];
        [emailaddress resignFirstResponder];
        
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Passcode can not be more than 4 digits" delegate:nil cancelButtonTitle:@"Ok!" otherButtonTitles: nil];
        [alert show];
        [alert release];
    }
}

/*Tapping the background will get rid of the keyboard.*/
- (IBAction)TapBackground:(id)sender{
    
    //Resign all keyboards from screen
    [secretQuestion resignFirstResponder];
    [secretAnswer resignFirstResponder];
    [passcode resignFirstResponder];
    [hint resignFirstResponder];
    [emailaddress resignFirstResponder];
    
    //If Picker is shown; then the current row will be saved into the sample question text field.
    if(!questionPicker.hidden){
        doneQuestion.hidden = true;
        questionPicker.hidden = true;
        
        secretQuestion.hidden = false;
        secretAnswer.hidden = false;
        passcode.hidden = false;
        hint.hidden = false;
        emailaddress.hidden = false;
        done.hidden = false;
        
        NSString *choice = [questions objectAtIndex:[questionPicker selectedRowInComponent:0]];
        secretQuestion.text = choice;
        
        [choice release];
    }
}

/*Tapping done on the keyboard will get rid of the keyboard*/
- (IBAction)TapDoneKeyboard:(id)sender{
    //Done will get rid of keyboard
    [sender resignFirstResponder];
}

/*Functions to animate the view upwards; to prevent the keyboard
overlaying the text fields*/
- (IBAction)textFieldDidBeginEditing:(UITextField *)textField
{
    [self animateTextField: textField up: YES];
}


- (IBAction)textFieldDidEndEditing:(UITextField *)textField
{
    [self animateTextField: textField up: NO];
}

- (void) animateTextField: (UITextField *) textField up: (BOOL) up
{
    const int movementDistance = 100; // tweak as needed
    const float movementDuration = 0.3f; // tweak as needed
    
    int movement = (up ? -movementDistance : movementDistance);
    
    [UIView beginAnimations: @"anim" context: nil];
    [UIView setAnimationBeginsFromCurrentState: YES];
    [UIView setAnimationDuration: movementDuration];
    self.view.frame = CGRectOffset(self.view.frame, 0, movement);
    [UIView commitAnimations];
}
//end of view animation

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [[UIApplication sharedApplication]cancelAllLocalNotifications];
    
    NSArray *arr = [[NSArray alloc]initWithObjects:@"What is your mother's name?", @"What is your pet's name?", @"Your Highschool's name?", @"Where did you grow up?", @"Your favourite medication?", @"Your Son's name?", nil];
    self.questions = arr;
    
    [arr release];
    
    aD = [[UIApplication sharedApplication] delegate];
    
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

/*release all outlets*/
- (void) dealloc{
    
    [mm release];
    [aD release];
    
    [secretAnswer release];
    [secretQuestion release];
    [secretQuestionButton release];
    [passcode release];
    [emailaddress release];
    [hint release];
    [done release];
    [emailaddress  release];
    
    [questionPicker release];
    [questions release];
    [done release];
    
    [super dealloc];
}

@end